"""User model."""
from app import db
from app.models.base import BaseModel


class User(BaseModel):
    """User model representing app users."""
    
    __tablename__ = 'users'
    
    wechat_openid = db.Column(db.String(128), unique=True, nullable=False, index=True)
    nickname = db.Column(db.String(128))
    avatar_url = db.Column(db.String(512))
    home_latitude = db.Column(db.Float)
    home_longitude = db.Column(db.Float)
    home_accuracy = db.Column(db.Float)
    preferences = db.Column(db.JSON, default=dict)
    
    # Relationships
    sessions = db.relationship('WalkingSession', back_populates='user', lazy='dynamic')
    music_library = db.relationship('Music', back_populates='user', lazy='dynamic')
    
    def to_dict(self):
        """Convert user to dictionary."""
        return {
            'id': self.id,
            'wechat_openid': self.wechat_openid,
            'nickname': self.nickname,
            'avatar_url': self.avatar_url,
            'home_location': {
                'latitude': self.home_latitude,
                'longitude': self.home_longitude,
                'accuracy': self.home_accuracy
            } if self.home_latitude and self.home_longitude else None,
            'preferences': self.preferences,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
